<template>
  <div class="common-list comp-clients"
       :class="{ 'comp-clients--depts': !role || role === 'holder' || role === 'officer' }"
       v-loading.fullscreen="loading">
    <div class="depts" v-if="!role || role === 'holder' || role === 'officer'">
      <div class="dept dept--lv0">
        <div class="name">组织架构</div>
      </div>
      <div>
        <el-form @submit.native.prevent>
          <el-form-item>
            <el-input v-model="filters.deptName" size="small" clearable placeholder="请输入" :readonly="loading"
                      @change="handleFilterDept()"></el-input>
          </el-form-item>
          <el-form-item style="text-align: center">
            <el-button type="primary" size="small" plain @click="handleGetDepts()">加载部门</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-tree
        ref="deptsRef"
        class="filter-tree"
        :data="deptsTreeData"
        :props=" {
                  children: 'children',
                  label: 'name'
                }"
        :expand-on-click-node="false"
        @node-click="selectDept"
        :filter-node-method="filterNode">
      </el-tree>

      <!--            <template v-for="dept1 in deptsFilter">-->
      <!--                <div class="dept dept&#45;&#45;lv1" :key="dept1.id" :class="{ expanded: dept1.expanded, selected: dept1.id === filters.deptId }">-->
      <!--                    <div class="expand" @click="expandDept(dept1)"></div>-->
      <!--                    <div class="name" @click="selectDept(dept1)">-->
      <!--                        <div class="text" >{{ dept1.name }}</div>-->
      <!--                        <div class="flag" v-if="dept1.type">{{ dept1.typeText }}</div>-->
      <!--                    </div>-->
      <!--                </div>-->
      <!--                <template v-for="dept2 in dept1.depts">-->
      <!--                    <div class="dept dept&#45;&#45;lv2" :key="dept2.id" :class="{ expanded: dept2.expanded, selected: dept2.id === filters.deptId }" v-if="dept1.expanded">-->
      <!--                        <div class="expand" @click="expandDept(dept2)"></div>-->
      <!--                        <div class="name" @click="selectDept(dept2)">-->
      <!--                            <div class="text">{{ dept2.name }}</div>-->
      <!--                            <div class="flag" v-if="dept2.type">{{ dept2.typeText }}</div>-->
      <!--                        </div>-->
      <!--                    </div>-->
      <!--                    <template v-for="dept3 in dept2.depts">-->
      <!--                        <div class="dept dept&#45;&#45;lv3" :key="dept3.id" :class="{ expanded: dept3.expanded, selected: dept3.id === filters.deptId }" v-if="dept1.expanded && dept2.expanded">-->
      <!--                            <div class="expand" @click="expandDept(dept3)"></div>-->
      <!--                            <div class="name" @click="selectDept(dept3)">-->
      <!--                                <div class="text">{{ dept3.name }}</div>-->
      <!--                                <div class="flag" v-if="dept3.type">{{ dept3.typeText }}</div>-->
      <!--                            </div>-->
      <!--                        </div>-->
      <!--                        <template v-for="dept4 in dept3.depts">-->
      <!--                            <div class="dept dept&#45;&#45;lv4" :key="dept4.id" :class="{ expanded: dept4.expanded, selected: dept4.id === filters.deptId }" v-if="dept1.expanded && dept2.expanded && dept3.expanded">-->
      <!--                                <div class="expand" @click="expandDept(dept4)"></div>-->
      <!--                                <div class="name" @click="selectDept(dept4)">-->
      <!--                                    <div class="text">{{ dept4.name }}</div>-->
      <!--                                    <div class="flag" v-if="dept4.type">{{ dept4.typeText }}</div>-->
      <!--                                </div>-->
      <!--                            </div>-->
      <!--                            <template v-for="dept5 in dept4.depts">-->
      <!--                                <div class="dept dept&#45;&#45;lv5" :key="dept5.id" :class="{ expanded: dept5.expanded, selected: dept5.id === filters.deptId }" v-if="dept1.expanded && dept2.expanded && dept3.expanded && dept4.expanded">-->
      <!--                                    <div class="expand" @click="expandDept(dept5)"></div>-->
      <!--                                    <div class="name" @click="selectDept(dept5)">-->
      <!--                                        <div class="text">{{ dept5.name }}</div>-->
      <!--                                        <div class="flag" v-if="dept5.type">{{ dept5.typeText }}</div>-->
      <!--                                    </div>-->
      <!--                                </div>-->
      <!--                            </template>-->
      <!--                        </template>-->
      <!--                    </template>-->
      <!--                </template>-->
      <!--            </template>-->
    </div>
    <div class="common-list__head">
      <el-input class="filter" v-model="deptSelect.name" :title="deptSelect.name" disabled size="small" style="width: 240px" clearable placeholder="请输入"
                :readonly="loading">
        <span slot="prepend">选中部门</span>
      </el-input>
      <el-input class="filter" v-model="filters.number" size="small" style="width: 240px" clearable placeholder="请输入"
                :readonly="loading" @change="search(true)">
        <span slot="prepend">工号</span>
      </el-input>
      <el-input class="filter" v-model="filters.name" size="small" style="width: 240px" clearable placeholder="请输入"
                :readonly="loading" @change="search(true)">
        <span slot="prepend">姓名</span>
      </el-input>
      <!-- <el-select class="filter" v-model="filters.sex" size="small" style="width: 140px" @change="search(true)">
          <el-option label="不限性别" :value="null"></el-option>
          <el-option v-for="data in env.userSexs" :key="data.id" :label="data.name" :value="data.value"></el-option>
      </el-select> -->
      <el-input class="filter" v-model="filters.mobile" size="small" style="width: 240px" clearable placeholder="请输入"
                :readonly="loading" @change="search(true)">
        <span slot="prepend">手机号</span>
      </el-input>
      <el-checkbox v-model="filters.onlySelf" size="small" :readonly="loading">不包含下级</el-checkbox>

      <el-select class="filter" v-model="filters.role" size="small" style="width: 140px" @change="search(true)"
                 v-if="!role">
        <el-option label="不限角色" :value="null"></el-option>
        <el-option v-for="data in env.userRoles" :key="data.id" :label="data.name" :value="data.value"></el-option>
      </el-select>
      <el-select class="filter" v-model="filters.deptRole" size="small" style="width: 140px" @change="search(true)"
                 v-if="!role">
        <el-option label="不限身份" :value="null"></el-option>
        <el-option v-for="data in env.deptRoles" :key="data.value" :label="data.name" :value="data.value"></el-option>
      </el-select>
      <el-select class="filter" v-model="filters.banned" size="small" style="width: 140px" @change="search(true)">
        <el-option label="不限冻结状态" :value="null"></el-option>
        <el-option v-for="data in env.userBanneds" :key="data.id" :label="data.name" :value="data.value"></el-option>
      </el-select>
      <el-select class="filter" v-model="filters.flag" size="small" style="width: 140px" @change="search(true)">
        <el-option label="不限激活状态" :value="null"></el-option>
        <el-option v-for="data in env.userEnable" :key="data.id" :label="data.name" :value="data.value"></el-option>
      </el-select>
      <el-button class="filter" type="primary" size="small" @click="activation()">一键激活</el-button>

      <el-button class="filter" type="primary" size="small" @click="search()">查询</el-button>
      <el-button class="filter" type="plain" size="small" @click="reset(true)">重置</el-button>
    </div>
    <div class="common-list__nect">
      <slot name="head" :loading="loading" :filters="filters" :selects="selects"></slot>
    </div>
    <div class="common-list__body">
      <el-table ref="table" size="medium" height="100%" :data="list" @header-click="onTableHeaderClick"
                @row-click="onTableRowClick" @selection-change="onTableSelectionChange">
        <el-table-column type="selection" align="center" v-if="select"></el-table-column>
        <el-table-column label="头像/姓名/工号" min-width="8">
          <template #default="scope">
            <img style="float: left; margin-right: 10px; border-radius: 20px; width: 40px; height: 40px"
                 :src="scope.row.avatar || require('../assets/user-avatar.png')"/>
            <a :href="'#/org/client?clientId=' + scope.row.id" v-if="link && access('org')">{{ scope.row.name }}</a>
            <span v-else>{{ scope.row.name }}</span>
            <div style="margin-left: 50px; color: #aaa">{{ scope.row.number }}</div>
          </template>
        </el-table-column>
        <el-table-column label="性别" min-width="2">
          <template #default="scope">{{ scope.row.sexText }}</template>
        </el-table-column>
        <el-table-column label="手机号" min-width="6">
          <template #default="scope">{{ scope.row.mobile || "-" }}</template>
        </el-table-column>
        <el-table-column label="身份" min-width="6">
          <template #default="scope">{{ scope.row.roleDept || "-" }}</template>
        </el-table-column>
        <el-table-column label="角色" min-width="4" v-if="!role">
          <template #default="scope">{{ scope.row.roleText }}</template>
        </el-table-column>
        <el-table-column label="所属部门" min-width="12" v-if="!role || role === 'holder' || role === 'officer'">
          <template #default="scope">
            <template v-if="scope.row.depments.length > 0">
              <div v-for="depment in scope.row.depments" :key="depment.id">
                <span>{{ depment.dept.name }}</span>
                <span> - </span>
                <span>{{ depment.duty }}</span>
              </div>
            </template>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="所属单位" min-width="12" v-if="!role || role === 'holder' || role === 'officer'">
            <template #default="scope">
                <template v-if="scope.row.dapments.length > 0">
                    <div v-for="dapment in scope.row.dapments" :key="dapment.id">
                        <span>{{ dapment.dapt.name }}</span>
                        <span> - </span>
                        <span>{{ dapment.duty }}</span>
                    </div>
                </template>
                <span v-else>-</span>
            </template>
        </el-table-column> -->
        <el-table-column label="冻结状态" min-width="4">
          <template #default="scope">
            <span class="el-status--danger" v-if="scope.row.banned === 'yes'"></span>
            <span class="el-status--success" v-else-if="scope.row.banned === 'not'"></span>
            <span>{{ scope.row.bannedText }}</span>
          </template>
        </el-table-column>
        <el-table-column label="激活状态" min-width="4">
          <template #default="scope">
            <span class="el-status--danger" v-if="scope.row.flag === 'not'"></span>
            <span class="el-status--success" v-else-if="scope.row.flag === 'yes'"></span>
            <span>{{ scope.row.bandFlag }}</span>
          </template>
        </el-table-column>
        <el-table-column label="最近活跃时间" min-width="6">
          <template #default="scope">{{ scope.row.lastActiveAt || "-" }}</template>
        </el-table-column>
        <el-table-column label="操作" width="160" v-if="$slots.body || $scopedSlots.body">
          <template #default="scope">
            <slot name="body" :loading="loading" :filters="filters" :data="scope.row" :selects="selects"></slot>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="common-list__foot" :class="{ 'common-list__foot--slot': $slots.foot || $scopedSlots.foot }">
      <el-pagination background layout="total,sizes,prev,pager,next,jumper" :page-sizes="[10, 20, 50, 100]"
                     :page-size="filters.linage" :current-page="filters.page" :total="filters.total"
                     @size-change="onTableLinageChange" @current-change="onTablePageChange"></el-pagination>
      <slot name="foot" :loading="loading" :filters="filters" :selects="selects"></slot>
    </div>
  </div>
</template>

<script>
import mixin from "../mixin";
import {object, array, string, int, session, cache} from "../util";
import * as deptUtil from '@/utils/deptUtil'
import {deptApi} from '@/api/dept'

export default {
  name: "comp-clients",
  mixins: [mixin],
  props: {
    role: {type: String, default: null},
    select: {type: Boolean, default: false},
    link: {type: Boolean, default: false},
  },
  data: () => ({
    loading: false,
    filters: {
      ids: null,
      number: null,
      name: null,
      sex: null,
      mobile: null,
      role: null,
      deptId: null,
      deptIds: null,
      banned: 'not',
      flag: 'yes',
      linage: 10,
      page: 1,
      total: 0,
      deptName: undefined,
      onlySelf: false,
      deptRole: null
    },
    list: [],
    selects: [],
    depts: [],
    deptsFilter: [],
    deptsTreeData: [],
    deptSelect:{},
    managerQuNums: managerQuNums
  }),
  methods: {
    activation() {
      if (this.loading) return;
      if (!this.filters.ids || this.filters.ids.length == 0) return this.plugins.modal.toast("请先勾选要激活的用户哦！", "warning");
      // let content = " <span style='color:red;'>" + (orders.length > 1 ? "勾选的" + orders.length + "个事项" : orders[0].title) + "</span> 吗？";
      this.plugins.modal.alert("", "确定激活这些用户", "warning", ["确定激活", "再想想"]).then((ok) => {
        if (!ok) {
          // this.filters.ids =null;
          return;
        }
        this.loading = true;
        this.plugins.user.activationfun(this.filters.ids).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            this.plugins.modal.toast("激活成功！", "success");
            this.search();
          } else {
            this.plugins.modal.alert("激活失败", res.code + "：" + res.msg, "error");
          }
        });
      });
      // console.log(this.filters.ids);
    },
    reset(deep) {
      let data = deep ? {} : object(session([this.env.key, this.$options.name, "filters", this.$route.fullPath]));
      this.filters = Object.assign(this.$options.data().filters, data);
      this.filters.deptId = this.profile.depments?.[0]?.dept.id
      if(this.link){
        this.deptSelect = this.filters.deptId?{
        ...this.profile.depments?.[0],
        name: this.profile.depments?.[0]?.dept?.name
      }:{}
      }
      this.search(false);
    },
    validate() {
      let filters = this.filters;
      filters.ids = null;
      filters.role = this.role || filters.role;
      filters.total = Math.max(int(filters.total), 0);
      filters.linage = Math.max(int(filters.linage), 1);
      filters.page = Math.max(Math.min(int(filters.page), Math.ceil(filters.total / filters.linage)), 1);
      session([this.env.key, this.$options.name, "filters", this.$route.fullPath], filters);
    },
    onTableHeaderClick() {
      this.select && this.$refs.table.toggleAllSelection();
    },
    onTableRowClick(row) {
      this.select && this.$refs.table.toggleRowSelection(row);
    },
    onTableLinageChange(value) {
      this.filters.linage = value;
      this.search(true);
    },
    onTablePageChange(value) {
      this.filters.page = value;
      this.search(true);
    },
    onTableSelectionChange(selects) {
      // console.log(selects);
      let weijiselects = selects.filter(item => item.flag == "not")
      if (selects.length === 0) {
        this.filters.ids = null
      }
      console.log(weijiselects);
      this.filters.ids = weijiselects.map((data) => data.id);
      // console.log(this.filters.ids);
      this.selects = selects;
    },
    expandDept(dept) {
      if (dept.expanded) {
        dept.expanded = false;
      } else if (dept.loaded) {
        dept.expanded = true;
      } else {
        this.loading = true;
        this.plugins.user.getDepts({deptId: dept.id, linage: 1000, page: 1}).then((res) => {
          this.loading = false;
          if (res.code === 0) {
            dept.depts = res.data.list;
            dept.depts.forEach((item) => {
              item.dept.name = dept.name;
              item.level = dept.level + 1;
            });
            dept.depts.sort((a, b) => {
              let a1 = a.city.id;
              let a2 = a.county.id;
              let a3 = a.sort;
              let b1 = b.city.id;
              let b2 = b.county.id;
              let b3 = b.sort;
              return a1 === b1 ? a2 === b2 ? b3 - a3 : a2 - b2 : a1 - b1;
            });
            dept.expanded = true;
            dept.loaded = true;
          } else {
            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
          }
        });
      }
    },
    selectDept(dept) {
      this.filters.deptId = this.filters.deptId === dept.id ? "" : dept.id;
      this.deptSelect = this.filters.deptId?dept:{}
      this.search(true);
    },
    search(clean) {
      console.log('this.filters.deptId',this.filters.deptId)
      if (this.loading) return;
      this.filters.deptIds = null
      if(!this.filters.deptId
        && this.profile.number != 'administrator'
        && !this.managerQuNums.includes(this.profile.number)){
        this.filters.deptIds = this.deptsTreeData?.map(item=>item.id)
      }
      if (clean) this.list = [];
      if (clean) this.selects = [];
      let filters = this.filters;
      this.validate();
      this.loading = true;
      this.plugins.user.getClients(filters).then((res) => {
        this.loading = false;
        this.list = [];
        this.selects = [];
        this.$nextTick(() => this.$refs.table.doLayout());
        if (res.code === 0) {
          console.log('用户',res.data)
          let data = res.data;
          data?.list?.forEach(user=>{
            user.roleDept = Array.from(new Set(user.depments.map(x=>{
              if(x.primary =='yes'){
                return '管理员'
              }else {
                return x.roleText
              }
            }))).join(',')
          })
          if (data.page > 1 && data.list.length === 0) {
            filters.total = 0;
            this.search();
          } else {
            filters.total = data.total;
            this.list = data.list;
            this.validate();
          }
        } else {
          filters.total = 0;
          this.validate();
          this.plugins.modal.toast("列表加载失败<br>" + res.code + "：" + res.msg, "error");
        }
      });
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.name.includes(value);
    },
    init() {
      this.reset()
      this.loading = true;
      this.plugins.user.call(async () => {
        const deptsCache = cache('depts')
        if (deptsCache) {
          this.depts = deptsCache || []
        }

        let length = this.depts.length;
        console.log('profile', this.profile);
        if (length === 0) this.depts = this.role && this.role === "staff" ? [] : [];
        // this.deptsFilter = this.depts
        // this.handleFilterDept()

        // 获取归属地相同的部门
        const depts = deptUtil.getDeptsByUserDeptsLocation(this.depts, this.profile.depments)
        console.log('depts', depts)
        // administrator看完所有的
        if (this.profile.number == 'administrator') {
          this.deptsTreeData = this.plugins.treeData.arrayToTree(this.depts, 'id', 'parentId', '')
        } else {
          // 从相同归属地的部门中找到所有归属地的父节点ID
          let parentIds = deptUtil.getParentIdsByDepts(depts)
          console.log('parentIds', parentIds)
          // 父节点的下属节点都作为根节点
          // parentIds = depts.filter(x=>parentIds.includes(x.parentId)).map(x=>x.id)
          this.deptsTreeData = []
          parentIds.forEach((parentId) => {
            if (parentId) {
              const dept = this.depts.find(x => x.id == parentId)
              this.deptsTreeData.push({
                ...dept,
                children: this.plugins.treeData.arrayToTree(this.depts, 'id', 'parentId', parentId)
              })
            } else {
              // 本来就是顶层的 parentId = ""
              this.deptsTreeData = this.deptsTreeData.concat(this.plugins.treeData.arrayToTree(this.depts, 'id', 'parentId', ''))
            }
          })
        }
        return {code: 0};
      }).then((res) => {
        this.loading = false;
        this.reset();
      });
    },
    handleFilterDept() {
      this.$refs.deptsRef.filter(this.filters.deptName)
    },
    async handleGetDepts() {
      this.loading = true;

      const depts2 = (await deptApi.getDeptsSimpleList(this.profile.depments?.[0]?.dept?.city?.id))?.data
      if(depts2?.length > 0){
        this.depts = (depts2 || []).map(x => {
          return {
            ...x,
            id: x.deptId+'',
            parentId: x.parentId ? x.parentId : '',
            name: x.deptName
          }
        })
        // 获取归属地相同的部门
        // const depts = deptUtil.getDeptsByUserDeptsLocation(this.depts, this.profile.depments)
        const depts = this.depts
        console.log('depts', depts)
        // administrator看完所有的
        if (this.profile.number == 'administrator') {
          this.deptsTreeData = this.plugins.treeData.arrayToTree(this.depts, 'id', 'parentId', '')
        } else {
          // 从相同归属地的部门中找到所有归属地的父节点ID
          let parentIds = deptUtil.getParentIdsByDepts(depts)
          console.log('parentIds', parentIds)
          // 父节点的下属节点都作为根节点
          // parentIds = depts.filter(x=>parentIds.includes(x.parentId)).map(x=>x.id)
          this.deptsTreeData = []
          parentIds.forEach((parentId) => {
            if (parentId) {
              const dept = this.depts.find(x => x.id == parentId)
              this.deptsTreeData.push({
                ...dept,
                children: this.plugins.treeData.arrayToTree(this.depts, 'id', 'parentId', parentId)
              })
            } else {
              // 本来就是顶层的 parentId = ""
              this.deptsTreeData = this.deptsTreeData.concat(this.plugins.treeData.arrayToTree(this.depts, 'id', 'parentId', ''))
            }
          })
        }
      }else {
        this.plugins.modal.toast("加载部门失败！", "error");
      }

      this.loading = false;
    },
  },
};
</script>

<style lang="scss">
.comp-clients {
  overflow: hidden;
}

.comp-clients--depts {
  padding-left: 302px;

  & > .depts {
    position: absolute;
    top: 0;
    left: 0;
    border: solid 1px #ddd;
    width: 280px;
    height: calc(100% - 2px);
    overflow-x: hidden;
    overflow-y: auto;
    scrollbar-width: none;

    &::-webkit-scrollbar {
      width: 6px;
      height: 1px;
    }

    &::-webkit-scrollbar-track {
      background-color: transparent;
    }

    &::-webkit-scrollbar-thumb {
      background-color: #ddd;
    }

    & > .dept {
      display: flex;
      align-items: flex-start;
      border-bottom: dashed 1px #ddd;
      user-select: none;
      cursor: pointer;

      & > .expand {
        flex: 0 0 auto;
        padding: 6px;
        width: 20px;
        height: 20px;
        color: #aaa;
        font-size: 16px;
        line-height: 20px;
        text-align: center;
        user-select: none;
        cursor: pointer;

        &:before {
          content: "+";
        }
      }

      & > .name {
        flex: 1 1 0;
        display: flex;
        align-items: flex-start;
        padding: 7px 6px 7px 0;

        & > .text {
          flex: 0 1 auto;
          min-height: 18px;
          color: #333;
          font-size: 14px;
          line-height: 18px;
        }

        & > .flag {
          flex: 0 0 auto;
          margin-left: 0.5em;
          height: 18px;
          color: #999;
          font-size: 14px;
          line-height: 18px;
        }
      }

      &.expanded {
        & > .expand {
          &:before {
            content: "-";
          }
        }
      }

      &.selected {
        background-color: #d9e5f5;

        & > .name {
          color: #1677ff;
        }
      }
    }

    & > .dept--lv0 {
      position: sticky;
      top: 0;
      left: 0;
      z-index: 1;
      background-color: white;

      & > .name {
        display: block;
        height: 18px;
        color: #333;
        font-size: 14px;
        font-weight: bold;
        line-height: 18px;
        text-align: center;
      }
    }

    & > .dept--lv1 {
      margin-left: 0;
    }

    & > .dept--lv2 {
      margin-left: 28px;
    }

    & > .dept--lv3 {
      margin-left: 56px;
    }

    & > .dept--lv4 {
      margin-left: 84px;
    }

    & > .dept--lv5 {
      margin-left: 112px;
    }
  }
}
</style>
